/**   
 * @project    : TestProject
 * @copyright  : (c) 2011 Wasu,ltd.
 * @package    : com.wasu.util
 * @created on : 2015-7-28 下午6:44:42
 * @author     : 王健
 */
package com.wasu.vod.utils;

import com.jcraft.jsch.*;
import org.apache.log4j.Logger;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 *@fileName   : SftpUtil.java
 *@description: TODO
 */
public class SftpUtil {

	private String server;   
		
	private int port;
	  
	private String username; 
	 
	private String password; 

	private ChannelSftp sftp;

	private Session sshSession = null;
	
	private Channel channel = null;
	  
	private final static Logger log = Logger.getLogger(SftpUtil.class);   
	/**
	* 
	* @param server
	* @param port
	* @param username
	* @param password
	*/
	public SftpUtil(String server, int port , String username, String password) {
	    this.server = server;   
	    this.port = port;
	    this.username = username;   
	    this.password = password;   
	    
	} 
	/**
	 *  
	 * @return
	 * @author 王健
	*/
	public boolean connect() {
		try{
			JSch jsch = new JSch();
			jsch.getSession(username, server, port);
			sshSession = jsch.getSession(username, server, port);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
		    channel = sshSession.openChannel("sftp");
			channel.connect();
			sftp = (ChannelSftp) channel;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
    /**  
     * 下载一个文件到默认的本地路径中  
     *   
     * @param fileName  
     *            文件名称(不含路径)  
     * @param delFile  
     *            成功后是否删除该文件  
     * @return  
     */  
    public boolean get(String remoteFileName,String localFileName,boolean delFile) { 
        return getFile(remoteFileName, localFileName, delFile);   
    } 
    /**  
     * 下载一个远程文件到本地的指定文件  
     *   
     * @param remoteAbsoluteFile  
     *            远程文件名(包括完整路径)  
     * @param localAbsoluteFile  
     *            本地文件名(包括完整路径)  
     * @return 成功时，返回true，失败返回false  
     */  
    public boolean getFile(String remoteAbsoluteFile, String localAbsoluteFile,   
            boolean delFile) {   
    	FileOutputStream output = null;   
        try { 
            //判断远程目录是否存在
            remoteAbsoluteFile = remoteAbsoluteFile.replace("\\", "/");
            String remoteDirectory=remoteAbsoluteFile.substring(0,remoteAbsoluteFile.lastIndexOf("/")+1); //远程目录
            String remoteFileName = remoteAbsoluteFile.substring(remoteAbsoluteFile.lastIndexOf("/")+1,remoteAbsoluteFile.length()); //远程文件名
            sftp.cd(remoteDirectory);
            // 处理传输   
            File file=new File(localAbsoluteFile);
            output = new FileOutputStream(file);
            sftp.get(remoteFileName, output);
            if(delFile){
            	sftp.rm(remoteFileName);
            }
            return true;   
        } catch (Exception e) {   
           e.printStackTrace();
           return false;   
        } finally {   
            try {   
                if (output != null) {   
                    output.close();   
                }   
                closeChannel();
            } catch (Exception e2) {   
            	e2.printStackTrace();
            }   
        }  
    } 
    /**  
     * 上传一个文件到默认的远程路径中  
     *   
     * @param fileName  
     *            文件名称(不含路径)  
     * @param delFile  
     *            成功后是否删除该文件  
     * @return  
     */  
    public boolean put(String remoteFileName,String localFileName, boolean delFile) {   
          return putFile(remoteFileName, localFileName, delFile);   
    } 
    /**  
     * 上传一个本地文件到远程指定文件  
     *   
     * @param remoteAbsoluteFile  
     *            远程文件名(包括完整路径)  
     * @param localAbsoluteFile  
     *            本地文件名(包括完整路径)  
     * @return 成功时，返回true，失败返回false  
     */  
    private boolean putFile(String remoteAbsoluteFile, String localAbsoluteFile,   
            boolean delFile) {
    	log.info("=====>远程文件:"+remoteAbsoluteFile+",本地文件:"+localAbsoluteFile);
    	remoteAbsoluteFile = remoteAbsoluteFile.replace("\\", "/");
        String remoteDirectory=remoteAbsoluteFile.substring(0,remoteAbsoluteFile.lastIndexOf("/")+1); //远程目录
        String remoteFileName = remoteAbsoluteFile.substring(remoteAbsoluteFile.lastIndexOf("/")+1,remoteAbsoluteFile.length()); //远程文件名
        FileInputStream input = null;
        try {
    		sftp.cd(remoteDirectory);
    		File file=new File(localAbsoluteFile);
    		input = new FileInputStream(file);
    		sftp.put(input, remoteFileName);
    		if (delFile) {   
                (new File(localAbsoluteFile)).delete(); //删除本地文件 
                log.info("delete " + localAbsoluteFile); 
            }
    		return true;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return false;
    	} finally {   
            try {   
                if (input != null) {   
                    input.close();   
                } 
                closeChannel();
            } catch (Exception e2) {  
            	e2.printStackTrace();
            }   
        }  
    } 
    /**
    * 删除文件
    * @param directory 要删除文件所在目录
    * @param deleteFile 要删除的文件
    * @param sftp
    */
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {
	    try {
	    	sftp.cd(directory);
	    	sftp.rm(deleteFile);
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
    }
    
    public List<String> readFile(String remoteAbsoluteFile) {
    	List<String> list = new ArrayList<String>();
    	BufferedReader reader = null;
    	try { 
            //判断远程目录是否存在
            remoteAbsoluteFile = remoteAbsoluteFile.replace("\\", "/");
            String remoteDirectory=remoteAbsoluteFile.substring(0,remoteAbsoluteFile.lastIndexOf("/")+1); //远程目录
            String remoteFileName = remoteAbsoluteFile.substring(remoteAbsoluteFile.lastIndexOf("/")+1,remoteAbsoluteFile.length()); //远程文件名
            sftp.cd(remoteDirectory);
            // 处理传输   
            InputStream ins = sftp.get(remoteFileName);
            reader = new BufferedReader(new InputStreamReader(ins)); 
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                    list.add(tempString);
            }
            return list;   
        } catch (Exception e) {   
           log.error("local file not found.", e);   
           e.printStackTrace();
           return list;   
        }finally {
        	try {
        		if(reader != null) {
        			reader.close();
        		}
        		closeChannel();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }
    /**  
     * 上传一个文件到远程指定文件  
     *   
     * @param remoteAbsoluteFile  
     *            远程文件名(包括完整路径)  
     * @param content  
     *            文件内容
     * @param encode  
     *            文件编码      
     */ 
    public boolean putContent(String remoteAbsoluteFile, String content, String encode) {   
    	log.info("=====>远程文件:"+remoteAbsoluteFile);
    	remoteAbsoluteFile = remoteAbsoluteFile.replace("\\", "/");
        String remoteDirectory=remoteAbsoluteFile.substring(0,remoteAbsoluteFile.lastIndexOf("/")); //远程目录
        String remoteFileName = remoteAbsoluteFile.substring(remoteAbsoluteFile.lastIndexOf("/")+1,remoteAbsoluteFile.length()); //远程文件名
        InputStream input = null;
        try {
        	//判断文件是否存在
        	try{ 
        		sftp.cd(remoteDirectory);
        	} catch (SftpException esftp) { 
        		 if(sftp.SSH_FX_NO_SUCH_FILE == esftp.id){
        			sftp.mkdir(remoteDirectory);
 			        sftp.cd(remoteDirectory);
        		 }
        	}
        	// 处理传输   
            input = new ByteArrayInputStream(content.getBytes(encode)); 
    		sftp.put(input, remoteFileName);
    		log.info("put 文件内容" + content);  
    		return true;
    	} catch (Exception e) {
    		e.printStackTrace();
    		return false;
    	} finally {   
            try {   
                if (input != null) {   
                    input.close();   
                } 
                closeChannel();
            } catch (Exception e2) {  
            	e2.printStackTrace();
            }   
        }  
    }
    /**
     * 关闭连接
     * @throws Exception
     * @author 王健
     */
    public void closeChannel(){
    	try{
    		if (channel != null) {
         	    channel.disconnect();
         	}
         	if (sshSession != null) {
         		sshSession.disconnect();
         	}
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    }
	/**
	 * @param args
	 * @author 王健
	 */
	public static void main(String[] args) {
		SftpUtil sftpUtil = new SftpUtil("125.210.144.11",21,"icds","icds123");
		/*if(sftpUtil.connect()){
			sftpUtil.put("/download/dk/SDDL_DKKK_123456_20141213.txt", "K:/SDDL_DKKK_123456_20141213.txt", false);
			
		}else {
			System.out.println("===连接失败");
		}*/
		if(sftpUtil.connect()){
			//sftpUtil.get("/download/rdk/SDDL_REDKKK_123456_20141213.txt", "K:/SDDL_REDKKK_123456_20141213.txt", false);
			//List lines = sftpUtil.readFile("/download/WASU_20150803.txt");
			//System.out.println("===" + lines.size());
			sftpUtil.putContent("/test.txt", "1111", "utf-8");
			
		}else {
			System.out.println("===连接失败");
		}
		sftpUtil.closeChannel();
	}

}
